package cn.ccew.common.utils;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;

public class JdbcUtils{

  @Autowired(required=false)
  private DataSource dataSource;
  

  private static char[] numbersAndLetters = null;
  private static Random randGen = null;
  private static Object initLock = new Object();

  public Connection getConnection()  throws SQLException, PropertyVetoException
  {
    return this.dataSource.getConnection();
  }

  
  public void free(ResultSet rs, Statement st, Connection conn) {
		try {
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (st != null)
					st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (conn != null)
					try {
						if(!conn.isClosed())
							conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
			}
		}
	}

  public static String getId()  throws SQLException
  {
    Date currentTime = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
    return formatter.format(currentTime) + randomString(6);
  }

  public static String randomString(int length)
  {
    if (length < 1) {
      return null;
    }
    if (randGen == null) {
      synchronized (initLock) {
        if (randGen == null) {
          randGen = new Random();
          numbersAndLetters = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ".toCharArray();
        }
      }
    }
    char[] randBuffer = new char[length];
    for (int i = 0; i < randBuffer.length; i++) {
      randBuffer[i] = numbersAndLetters[randGen.nextInt(32)];
    }
    return new String(randBuffer);
  }
  
}